package cn.passlink.www.ServerImpl;

import cn.passlink.www.Enity.Article;
import cn.passlink.www.Mapper.ArticleDao;
import cn.passlink.www.Mapper.sysUserDao;
import cn.passlink.www.Server.ArticleServer;
import cn.passlink.www.Utils.JsonUtils;
import cn.passlink.www.Utils.RandomUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

//实现接口方法

@Service
@Slf4j
public class ArticleServerImpl implements ArticleServer {
    @Autowired
    private ArticleDao ArticleDao;
    @Autowired
    private sysUserDao sysUserDao;

    /**
     * getAll
     *
     * @param page_now
     * @param page_size
     * @param type
     * @param tags
     * @param key_words
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/14
     **/
    @Override
    public Map<String, Object> getAll(int page_now, int page_size, String type, String tags, String key_words) {
        //查询方式取决于tags，type，key_words的空置情况，关键词使用全文索引方式
        Integer start_index = (page_now - 1) * page_size;
        List<Article> list;
        String msg;
        // 数据总条目
        Integer page_all_num;
        page_all_num = ArticleDao.getCounts();
        try {
            //根据tags获取，全部返回，前端自动计算分页
            if (!tags.isEmpty() && type.isEmpty()) {
                //根据tags获取和key_words获取
                if (!key_words.isEmpty()) {
                    list = ArticleDao.findPageByTagKey(start_index, page_size, tags, key_words);
                    page_all_num = ArticleDao.findPageByTagKeyCounts(tags, key_words);
                    msg = "获取成功";
                    log.info("根据tags获取和key_words获取");
                } else {

                    list = ArticleDao.findPageByTag(start_index, page_size, tags);
                    page_all_num = ArticleDao.findPageByTagCounts(tags);
                    msg = "获取成功";
                    log.info("根据tags获取");
                }
                if (list == null) {
                    log.info("没有匹配的文章");
                    return JsonUtils.resultJson(200, "没有匹配的文章");
                }
                return JsonUtils.dataListJson(200, processArticles(list), msg, page_all_num);
            }

            //根据type获取，全部返回，前端自动计算分页
            if (!type.isEmpty()) {
                //根据type获取和key_words获取
                if (!key_words.isEmpty()) {
                    list = ArticleDao.findPageByTypeKey(start_index, page_size, type, key_words);
                    page_all_num = ArticleDao.findPageByTypeKeyCounts(type, key_words);
                    log.info("根据type获取和key_words获取");
                    msg = "获取成功";
                } else {

                    list = ArticleDao.findPageByType(start_index, page_size, type);
                    page_all_num = ArticleDao.findPageByTypeCounts(type);
                    log.info("根据type获取");
                    msg = "获取成功";
                }

                if (list == null) {
                    log.info("没有匹配的文章");
                    return JsonUtils.resultJson(200, "没有匹配的文章");
                }
                return JsonUtils.dataListJson(200, processArticles(list), msg, page_all_num);
            }

            //默认匹配时，需要把总数返回
            //根据key_words获取
            if (key_words.length() > 3) {
                list = ArticleDao.findPageByKey(start_index, page_size, key_words);
                page_all_num = ArticleDao.findPageByKeyCounts(key_words);
                log.info("根据key_words获取");
                msg = "获取成功";
            } else {

                list = ArticleDao.findPage(start_index, page_size);
                log.info("默认无匹配获取");
                msg = "获取成功";
            }

            if (list == null) {
                log.info("没有匹配的文章");
                return JsonUtils.resultJson(200, "没有匹配的文章");
            }
            return JsonUtils.dataListJson(200, processArticles(list), msg, page_all_num);
        } catch (Exception e) {
            log.error("获取错误", e);
            return JsonUtils.resultJson(500, "获取文章失败");

        }


    }

    // 修改 processArticle 方法，将 list 作为参数传入
    private List<Map<String, Object>> processArticles(List<Article> list) {
        List<Map<String, Object>> res_list = new ArrayList<>();
        for (Article item : list) {
            Map<String, Object> article = new HashMap<>();
            article.put("article_id", item.getArticle_id());
            article.put("title", item.getTitle());
            article.put("tags", item.getTags());
            article.put("type", item.getType());
            article.put("views", item.getViews());
            article.put("cover_image", item.getCover_image());
            article.put("create_time", item.getCreate_time());
            String body = item.getBody();
            if (body.length() > 50) {
                body = body.substring(0, 50) + "......"; // 只获取前50个字
            }
            article.put("body", body);
            try {
                // 获取用户名
                String user_id = ArticleDao.findUserIdByArticleId(item.getArticle_id());
                String username = sysUserDao.findUsernameById(user_id);
                article.put("username", username);
                article.put("comments_counts", ArticleDao.getCommentsCounts(item.getArticle_id()));
                res_list.add(article);
            } catch (Exception e) {
                log.error("处理错误", e);
                return null;

            }
        }

        return res_list;
    }

    /**
     * getById
     *
     * @param article_id
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/14
     **/
    @Override
    public Map<String, Object> getById(String article_id) {
        Map<String, Object> res = new HashMap<>();
        try {
            Article article = ArticleDao.findById(article_id);
            if (article == null) {
                log.info("没有匹配的文章");
                return JsonUtils.resultJson(200, "没有匹配的文章");
            }
            // 获取用户名
            String user_id = ArticleDao.findUserIdByArticleId(article_id);
            String username = sysUserDao.findUsernameById(user_id);
            res.put("article_id", article.getArticle_id());
            res.put("username", username);
            res.put("title", article.getTitle());
            res.put("tags", article.getTags());
            res.put("create_time", article.getCreate_time());
            res.put("body", article.getBody());
            res.put("type", article.getType());
            //更新阅读量
            ArticleDao.updateViews(article_id);
            return JsonUtils.dataJson(200, res, "获取文章成功");
        } catch (Exception e) {
            log.error("获取文章失败", e);
            return JsonUtils.resultJson(500, "获取文章失败");

        }

    }

    /**
     * getByTypeTags
     *
     * @param type
     * @param tags
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/14
     **/
    @Override
    public Map<String, Object> getByTypeTags(String type, String tags) {
        List<Article> list = ArticleDao.findByTypeTags(type, tags);
        if (list == null) {
            log.info("没有匹配的标题");
            return JsonUtils.resultJson(200, "没有匹配的标题");
        }

        List<Map<String, Object>> resList = new ArrayList<>();

        for (Article article : list) {
            Map<String, Object> data = new HashMap<>();
            // 处理每个Article对象
            data.put("article_id", article.getArticle_id());
            data.put("title", article.getTitle());
            resList.add(data);
        }


        return JsonUtils.dataListJson(200, resList, "获取标题成功", resList.size());
    }

    /**
     * getLog
     * 获取文章日志
     *
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/14
     **/


    @Override
    public Map<String, Object> getLog() {

        List<Article> list = ArticleDao.findByTime();
        if (list == null) {
            log.info("最近没有文章发布");
            return JsonUtils.resultJson(200, "最近没有文章发布");
        }
        List<Map<String, Object>> resList = new ArrayList<>();

        for (Article article : list) {
            Map<String, Object> data = new HashMap<>();

            String body = article.getBody();
            //        限制返回40字符
            if (body.length() > 40) {
                data.put("body", body.substring(0, 40));
            }
            // 处理每个Article对象
            data.put("article_id", article.getArticle_id());
            data.put("title", article.getTitle());
            data.put("create_time", article.getCreate_time());
            data.put("cover_image", article.getCover_image());
            resList.add(data);
        }

        return JsonUtils.dataListJson(200, resList, "获取日志成功", resList.size());

    }

    /**
     * pullArticle
     * 上传文章
     *
     * @param type
     * @param tags
     * @param title
     * @param body
     * @param cover_image
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/14
     **/


    @Override
    public Map<String, Object> pullArticle(String type, String tags, String title, String body, String cover_image, String user_id) {

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = formatter.format(date);
        Article article = new Article();
        try {
            int counts = sysUserDao.getArticlesCounts(user_id);
            if (counts > 200) {
                log.error("文章上传达到上限500");
                return JsonUtils.resultJson(500, "文章上传达到上限,请联系管理员增加容量！！！");
            }
            article.setArticle_id(RandomUtils.generateUniqueId());
            article.setVisibility_status(1);
            article.setType(type);
            article.setTags(tags);
            article.setTitle(title);
            article.setBody(body);
            article.setCover_image(cover_image);
            article.setCreate_time(formattedDate);
            article.setViews(0);

//        关系记录
            ArticleDao.pullUserID(user_id, article.getArticle_id());
//        存入数据库
            ArticleDao.pullArticle(article);
            //更新数量
            sysUserDao.updateArticlesCounts(user_id);
        } catch (Exception e) {
            log.error("文章上传失败", e);
            return JsonUtils.resultJson(500, "文章上传失败");
        }


        return JsonUtils.resultJson(200, "文章上传成功");
    }

    /**
     * updateArticle
     *
     * @param article_id
     * @param type
     * @param tags
     * @param title
     * @param body
     * @param cover_image
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/11/5
     **/

    @Override
    public Map<String, Object> updateArticle(String article_id, String type, String tags, String title, String body, String cover_image, String user_id) {

        //判断该文章是否属于该用户
        try {
            String userId = ArticleDao.findUserIdByArticleId(article_id);
            if (!userId.equals(user_id)) {
                log.error("该文章不属于该用户");
                return JsonUtils.resultJson(403, "文章修改失败");
            }

            Article article = ArticleDao.findById(article_id);
            if (article == null) {
                log.error("文章不存在，不是修改操作");
                return JsonUtils.resultJson(403, "文章修改失败");
            }
            article.setArticle_id(article_id);
            article.setType(type);
            article.setTags(tags);
            article.setTitle(title);
            article.setBody(body);

            if (!"noChange".equals(cover_image) && cover_image.length() > 8) {
                article.setCover_image(cover_image);
            }

            ArticleDao.updateArticle(article);
        } catch (Exception e) {
            log.error("文章修改失败", e);
            return JsonUtils.resultJson(403, "文章修改失败");
        }
        return JsonUtils.resultJson(200, "文章修改成功");

    }

    /**
     * delArticle
     * 删除文章
     *
     * @param article_id
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/14
     **/

    @Override
    public Map<String, Object> delArticle(String article_id, String user_id) {

        //判断该文章是否属于该用户
        try {
            String userId = ArticleDao.findUserIdByArticleId(article_id);
            if (!userId.equals(user_id)) {
                log.error("该文章不属于该用户");
                return JsonUtils.resultJson(403, "文章删除失败");
            }
            ArticleDao.delArticle(article_id);
            return JsonUtils.resultJson(200, "文章删除成功");
        } catch (Exception e) {
            log.error("文章删除失败", e);
            return JsonUtils.resultJson(403, "文章删除失败!!");
        }
    }

    @Override
    public Map<String, Object> getAllByUserId(String user_id) {
        try {
            List<Article> list = new ArrayList<>();
            if (user_id.length() <=8) {
                log.error("用户id长度错误");
                return JsonUtils.resultJson(403, "获取失败");
            }
            list = ArticleDao.findAllByUserId(user_id);
            if (list == null) {
                log.error("文章为空");
                return JsonUtils.resultJson(403, "没有匹配的文章");
            }
            return JsonUtils.dataListJson(200, processArticles(list), "获取日志成功", list.size());
        } catch (Exception e) {
            return JsonUtils.resultJson(500, "获取失败");
        }

    }

    //获取文章数目
    @Override
    public Map<String, Object> getarticleCounts() {
        try {
            int counts = ArticleDao.getCounts();
            return JsonUtils.dataJson(200, counts, "");
        }catch (Exception e){
            log.error("查询错误");
            return JsonUtils.resultJson(500, "查询错误");
        }

    }


}
